import { ref, reactive, watchEffect, watch } from 'vue';
import { useRoute } from 'vue-router';
import type * as Type from './type';
import * as Api from '@/api/taskInfo/taskInfo';
import * as Store from '@/store';
import moment from 'moment';
import type * as StoreType from '@/store/modules/task-info/type';
import router from '@/router';
import usePageTable from "./usePageTable";
import type * as ApiType from '@/api/taskInfo/taskInfo.d';

export default function useTabs () {
  // const route = useRoute();
  // const { id } = route;
  const currentId = ref(0);
  const PageTableHooks = usePageTable();
  let taskIdList = ref<Type.TaskIdList[]>(<Type.TaskIdList[]>[]);
  const TaskInfo = Store.useTaskInfo();

  watch(() => taskIdList.value, (newVal) => {
    localStorage.setItem('taskIdList', JSON.stringify(newVal));
    const index = newVal.findIndex(item => item.isActive);
    currentId.value = +newVal[index].id;
    if (index > -1) {
      getFetchTaskData(newVal[index].id);
    }
  }, {
    deep: true
  });

  const setTaskIdList = (id: string) => {
    taskIdList.value = JSON.parse(localStorage.getItem('taskIdList') || '[]');
    if (taskIdList.value.length !== 0) {
      const index = taskIdList.value.findIndex(
        (item) => item.id === id
      );
      if(taskIdList.value.length > 9){//超过10个删除
        taskIdList.value.pop()
      }
      if (index > -1) {
        const currentItem = taskIdList.value.splice(index, 1);
        taskIdList.value.unshift(...currentItem);
      } else {
        taskIdList.value.unshift({ id, isActive: true });
      }
      currentId.value = +id;
      trigger(currentId.value);
    } else {
      taskIdList.value.push({
        id,
        isActive: true,
      });
    }
  }

  const handleTabClick = (key: string | number) => {
    taskIdList.value.map((item, index) => {
      if (+item.id === key) {
        trigger(key);
      }
    })
  }

  const trigger = (index: number) => {
    taskIdList.value.map(item => {
      if (+item.id === index) {
        item.isActive = true;
      } else {
        item.isActive = false;
      }
    })
    localStorage.setItem('taskIdList', JSON.stringify(taskIdList.value));
  }

  const getFetchTaskData = async (id: string) => {
    const result = await Api.annoTask(id);
    const taskInfo: StoreType.TaskInfoState = {
      taskId: 0,
      titleContent: [],
      openTaskData: {
        taskName: '',
        taskMethodType: '',
        beginDate: '',
        endDate: '',
        totalUserNum: 0
      },
      contractTaskData: {
        taskName: '',
        taskMethodType: '',
        beginDate: '',
        endDate: ''
      },
      currentType: 0,
      imageLayout: ''
    };
    taskInfo.taskId = result.data.taskInfo.id;
    taskInfo.titleContent = [
      {
        label: "创建人",
        value: result.data.taskInfo.createUser.userName,
      },
      {
        label: "创建时间",
        value: moment(result.data.taskInfo.createTime).format('YYYY-MM-DD hh:mm:ss'),
      },
      {
        label: "任务状态",
        value: result.data.taskInfo.status,
      },
    ];
    taskInfo.currentType = result.data.annoUserInfo?.pubMethod;
    taskInfo.imageLayout = result.data.annoInfo.imageLayout;
    if (result.data.annoUserInfo && result.data.annoUserInfo.pubMethod === 1) {
      taskInfo.openTaskData = {
        taskName: result.data.taskInfo.name,
        beginDate: moment(result.data.annoUserInfo.beginDate).format('YYYY-MM-DD'),
        endDate: moment(result.data.annoUserInfo.endDate).format('YYYY-MM-DD'),
        taskMethodType: '开放式',
        totalUserNum: result.data.annoUserInfo.totalUserNum,
        remark: result.data.annoUserInfo.remark
      }
    } else {
      taskInfo.contractTaskData = {
        taskName: result.data.taskInfo.name,
        beginDate: moment(result.data.annoUserInfo?.beginDate).format('YYYY-MM-DD'),
        endDate: moment(result.data.annoUserInfo?.endDate).format('YYYY-MM-DD'),
        taskMethodType: '承包式',
        remark: result.data.annoUserInfo?.remark,
        tableData: []
      }
      const tableDataItem = {
        companyName: '',
        userName: ''
      };
      result.data.annoUserInfo && result.data.annoUserInfo.annoUserList.map(item => {
        tableDataItem.companyName = item.company.name;
        tableDataItem.userName = item.userList.map(it => it.userName).join('、');
        taskInfo.contractTaskData.tableData?.push(tableDataItem);
      });
    }
    TaskInfo.setTaskInfoState(taskInfo);
    getUserData();
    PageTableHooks.getTableData();
  }

  const handleDelete = (key: number) => {
    taskIdList.value = taskIdList.value.filter(item => item.id !== key.toString());
    localStorage.setItem('taskIdList', JSON.stringify(taskIdList.value));
    taskIdList.value.length > 0 && router.replace({
      path: "readSeries",
      query: {
        id: taskIdList.value[0].id
      }
    });
    taskIdList.value.length > 0 && (taskIdList.value[0].isActive = true);
    taskIdList.value.length === 0 && router.back();
    // id && +id === key && taskIdList.value.length > 0 
  }

  const userList = ref<ApiType.UserListData[]>([]);

  const getUserData = async () => {
    const result = await Api.getUserList(+TaskInfo.taskId);
    result.data.list && (userList.value = result.data.list);
  }

  return {
    ...PageTableHooks,
    currentId,
    taskIdList,
    userList,
    setTaskIdList,
    handleTabClick,
    handleDelete
  }
}